/** @file    FormBuildingManager.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormBuildingManager.cpp 2873 2010-08-08 19:06:41Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormBuildingManager class.
 * The header for this class can be found in FormBuildingManager.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "FormBuildingManager.h"
 #include "ui_FormBuildingManager.h"

 #include <framework/gui/widgets/wBuilding_BuildingObject.h>
// #include <core/List.h>

// #include <QtGui/QInputDialog>
// #include <QtGui/QMessageBox>
// #include <framework/gui/GuiUtilities.h>


using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormBuildingManager, "wosh::gui::IWidgetGeneric", 1.0, _static_FormBuildingManager )
 WOSH_GUI_MAP(wosh::gui::FormBuildingManager, "wosh::interfaces::services::BuildingManager", 0.0, _static_Map_FormBuildingManager )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

FormBuildingManager::FormBuildingManager(QWidget *parent)
	: IWidgetGeneric(parent) {
	this->m_ui = new Ui::FormBuildingManager();
	this->m_ui->setupUi(this);

	IWidgetGeneric::setTargetURI("*:Building");
	buildMenus();

	// register to BUS
	BusBuilding.setMessageHandler(this);
	WRESULT bus_connected = BusBuilding.connect( _Bus_Building, Bus::ACTION_DEFERRED | Bus::BUS_CREATE_IF_MISSING );
	(void)bus_connected;

	// tab Building Map [0]


	// tab Building Tree [1]
	this->treeModel = new WoshBuidlingObjectTreeModel( NULL, this);
	this->m_ui->treeViewBObj->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->treeViewBObj, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(treeViewBObj_ContextMenu(const QPoint&)) );
	connect(this->m_ui->treeViewBObj, SIGNAL(doubleClicked(const QModelIndex&)),this, SLOT(bObj_doubleClicked(const QModelIndex&)) );
	this->m_ui->treeViewBObj->setModel(this->treeModel);
	connect(this->m_ui->wUpBarBObjTree, SIGNAL(updateClicked()), this, SLOT(refreshTree()));

	// tab Building Table [2]
	this->m_ui->tableViewBObj->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewBObj, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewBObj, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableBObjContextMenuRequested(const QPoint&, const QModelIndex&)) );
	connect(this->m_ui->tableViewBObj, SIGNAL(tableItemDoubleClicked(const QModelIndex&)),this, SLOT(bObj_doubleClicked(const QModelIndex&)) );
 }

FormBuildingManager::~FormBuildingManager() {
	delete this->m_ui;
 }

void FormBuildingManager::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBuildingManager::refreshAll() {
	this->setWindowTitle( QString("Building Manager [%1]").arg(this->getTargetURI().getKernelName().c_str()) );
	executeRemoteMethod( _METHOD_List );
	refreshTree();
	this->m_ui->tableViewBObj->refreshData();
//	this->m_ui->wUpBarBuildingObjects->sayRetrieving();
//	this->m_ui->progressBar->setValue(1);
 }

void FormBuildingManager::refreshTree() {
	executeRemoteMethod( _BuildingManager_METHOD_tree, Variant(this->m_ui->chkTreeShowChildren->isChecked()) );
	this->m_ui->wUpBarBObjTree->sayRetrieving();
 }

void FormBuildingManager::reDrawAll() {
	this->m_ui->wBuildingRenderer->refreshAll();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBuildingManager::buildMenus() {
	this->menuBObjTitle = new QAction(this);
	this->menuBObjTitle->setEnabled(false);

	this->menuBObjTree = new QMenu(this);
	this->menuBObjTree->addAction(this->menuBObjTitle);
	this->menuBObjTree->addSeparator();

	this->menuBObjTable = new QMenu(this);
	this->menuBObjTable->addAction(this->menuBObjTitle);
	this->menuBObjTable->addSeparator();
 }

void FormBuildingManager::tableBObjContextMenuRequested( const QPoint& pos, const QModelIndex& index ) {
	if ( !index.isValid() ) return;
	QPoint globalPos = this->mapToGlobal(pos);
	Variant bObjName = this->m_ui->tableViewBObj->getCurrentItemAsVariantAtCol(0);
	Variant bObjType = this->m_ui->tableViewBObj->getCurrentItemAsVariantAtCol(1);
	this->menuBObjTitle->setText( bObjName.toString().c_str() );
	this->menuBObjTitle->setIcon( GuiUtilities::createIconFor(bObjType.toString()) );
	QAction* selected = this->menuBObjTable->exec( globalPos );
	if ( selected == NULL ) {
	
	 }
 }

void FormBuildingManager::treeViewBObj_ContextMenu( const QPoint& pos ) {
	QPoint globalPos = this->mapToGlobal(pos);
	QModelIndex index = this->m_ui->treeViewBObj->indexAt(pos);
	if ( !index.isValid() ) return;
	TreeNode* item = static_cast<TreeNode*>(index.internalPointer());
	if ( item == NULL || item->getContent() == NULL ) return;
	const wosh::building::BuildingObject* bObj = item->getContent()->as<wosh::building::BuildingObject>();
	if ( bObj == NULL ) return;
	this->menuBObjTitle->setText( bObj->getName().c_str() );
	this->menuBObjTitle->setIcon( GuiUtilities::createIconFor(bObj->getInterfaces().getImplementedClass().getName()) );
	QAction* selected = this->menuBObjTree->exec( globalPos );
	if ( selected == NULL ) {
	 }

 }

void FormBuildingManager::bObj_doubleClicked( const QModelIndex& index ) {
	if ( !index.isValid() ) return;
	TreeNode* item = static_cast<TreeNode*>(index.internalPointer());
	if ( item == NULL || item->getContent() == NULL ) return;
	const wosh::building::BuildingObject* bObj = item->getContent()->as<wosh::building::BuildingObject>();
	if ( bObj == NULL ) return;
	
	wBuilding_BuildingObject* wBobj = new wBuilding_BuildingObject();
	wBobj->loadObject(bObj);
	wBobj->show();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBuildingManager::updateBObjFromTree( const TreeNode* node ) {
	if ( node == NULL ) return;
	if ( node->hasContent() ) {
		const wosh::building::BuildingObject* bObj = node->getContent()->as<wosh::building::BuildingObject>();
		this->m_ui->wBuildingRenderer->updateObject(bObj);
	 }
	TreeNode::ChildConstIterator it;
	const TreeNode::ChildConstIterator it_end = node->getChildren().end();
	for( it=node->getChildren().begin(); it!=it_end; ++it ) {
		const TreeNode* child = static_cast<const TreeNode*>(*it);
		updateBObjFromTree(child);
	 }
	this->m_ui->wBuildingRenderer->refreshCombos();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormBuildingManager::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() || !message.getContent()->isResponse() ) return;
	if ( message.getSourceBus() == _Bus_Building ) {
	 }
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	this->m_ui->tableViewBObj->evalResponse(response);

	if ( response->getMethod() == _BuildingManager_METHOD_tree ) {
		if ( !response->hasData() || !response->getData()->isKindOf<Tree>() ) return;
		const Tree* tree = response->getData()->as<Tree>();
		this->treeModel->loadTree(tree);
		this->m_ui->treeViewBObj->header()->setResizeMode(0, QHeaderView::Stretch);
		this->m_ui->treeViewBObj->resizeColumnToContents(0);
		this->m_ui->wUpBarBObjTree->sayReady();

		updateBObjFromTree( tree->getRoot() );
		return;
	 }

	promptMethodResponse( message, false );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
